package stud.mpgame.network.service.time;

import flash.Lib;

import stud.mpgame.network.NetworkMonitor;

import stud.mpgame.network.service.ping.PingNotificationMessageDescription;
import stud.mpgame.network.service.ping.PingNotificationUserObject;

/**
 * ...
 * @author pavel[f.pavel91@gmail.com]
 */

class TimeService {
	
	private var differenceTime:Float;
	private var pingNotificationsAmount:Int;
	
	public function new(networkMonitor:NetworkMonitor) {
		this.differenceTime = 0;
		this.pingNotificationsAmount = -5;
        networkMonitor.getMessageDispatcher().addMessageReceivedListener(PingNotificationMessageDescription.getInstance(), pingNotificationReceived);		
	}
	
	public function getDifferenceTime():Int {
		return Std.int(differenceTime);
	}
	
	public function getLocalTime():Int {
        return Lib.getTimer();
    }
	
    public function getServerTime():Int {
        return getLocalTime() + Std.int(differenceTime);
    }
	
    public function pingNotificationReceived(message:Message):Void {
		pingNotificationsAmount++;
		//TODO Wrong! start
		if (pingNotificationsAmount <= 0)
			return;
		//TODO WRONG! end
        var pingNotificationUserObject:PingNotificationUserObject = cast(message.getUserObject(PingNotificationUserObject), PingNotificationUserObject);
		var ping:Int = pingNotificationUserObject.getPing();
		var currentDifferenceTime:Int = message.getSentTime() - message.getReceivedTime() + ping;
		differenceTime += (currentDifferenceTime - differenceTime)/pingNotificationsAmount;
		trace("PING = " + ping + " DIFF TIME: " + differenceTime);
    }	
	
}